
package com.fyzk.base;

import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;


/**
 * 带底部菜单的封装类
 *
 */
public class IBaseActivity extends BaseActivity {

	protected String currentFg;//当前显示的fragment
	
	/**
	 * 切换内容 不支持返回前一个
	 * @param fragment
	 */
	public void changeFragment(Fragment fragment,int id){
		changeFragment(fragment,false,id);
	}
	
	/**
	 * 切换内容
	 * @param fragment
	 * @param canBack  是否可以返回上个fragment
	 */
	public void changeFragment(Fragment fragment,boolean canBack,int id){  
        FragmentManager fm = getSupportFragmentManager();  
        FragmentTransaction transaction = fm.beginTransaction(); 
        transaction.replace(id, fragment);  
        if(canBack){
        	transaction.addToBackStack(null);
        } else {
        	//不支持返回 清空返回栈
        	clearAllBackFragment();
        }
        transaction.commitAllowingStateLoss();  
//        if(fm.getFragments() != null){
//        	LogUtil.d("fragment size = "+fm.getFragments().size());
//        }
    }
	
	/**
	 * 切换fragment 并能返回上一个fragment
	 * @param currentFg  当前的fragment
	 * @param newFg    要显示的新的fragment
	 * @param canBack    是否返回上一个
	 * @param isRefresh  是否销毁当前的fragment 以达到返回后刷新界面数据效果 true 销毁  false 不销毁
	 * @param id         需要替换的布局
	 */
	public void changeFragment(Fragment currentFg,Fragment newFg,boolean canBack,boolean isRefresh,int id){
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        if(isRefresh){
        	transaction.replace(id, newFg);  
        } else {
        	//不销毁
        	if(currentFg != null){
        		transaction.hide(currentFg);
        	}
        	if(!newFg.isAdded()){
        		transaction.add(id, newFg,newFg.getClass().getName());
        	} else {
        		transaction.show(newFg);
        	}
        }
        
        if(canBack){
        	transaction.addToBackStack(null);
        }
        transaction.commitAllowingStateLoss();  
    }
	
    
	/**
	 * 返回上一个fragment
	 */
	public void backFragment(){
		 FragmentManager fm = getSupportFragmentManager();  
		 fm.popBackStack();
	}
	
	/**
	 * 清空返回栈中所有的fragment
	 */
	public void clearAllBackFragment(){
		FragmentManager fm = getSupportFragmentManager();  
		fm.popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE); //清空所有栈
	}
	
	/**
	 * 获取栈中fragment的数量
	 * @return
	 */
	public int getFragmentCount(){
		FragmentManager fm = getSupportFragmentManager();
		List<Fragment> fgList = fm.getFragments();
		if(null != fgList){
			return fgList.size();
		} else {
			return 0;
		}
	}



}

